package utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.*;


public class HttpClientUtil {
	private static Log logger = LogFactory.getLog(HttpClientUtil.class);

	public static void getRequest(String url){
		
		CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response1 = httpclient.execute(httpGet);
            // The underlying HTTP connection is still held by the response object
            // to allow the response content to be streamed directly from the network socket.
            // In order to ensure correct deallocation of system resources
            // the user MUST call CloseableHttpResponse#close() from a finally clause.
            // Please note that if response content is not fully consumed the underlying
            // connection cannot be safely re-used and will be shut down and discarded
            // by the connection manager.
            try {
                System.out.println(response1.getStatusLine());
                HttpEntity entity1 = response1.getEntity();
                // do something useful with the response body
                // and ensure it is fully consumed
                EntityUtils.consume(entity1);
            } finally {
                response1.close();
            }

        } catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
            try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
	}
	
	public static String postRequest(String url, String jsonParam) throws Exception{
		CloseableHttpClient httpclient = HttpClients.createDefault();
		logger.info(":::URL:" + url + ";JsonParam:" + jsonParam);
		String body = "{}";
//		 String str= post("https://localhost:443/ssl/test.shtml","name=12&page=34","application/x-www-form-urlencoded", "UTF-8", 10000, 10000);
        try {
            HttpPost httpPost = new HttpPost(url);
            HttpEntity entity = new StringEntity(jsonParam, ContentType.create("application/x-www-form-urlencoded", "UTF-8"));
            httpPost.setEntity(entity);
            CloseableHttpResponse response2 = httpclient.execute(httpPost);

            try {
                System.out.println(response2.getStatusLine());
                HttpEntity entity2 = response2.getEntity();
                // do something useful with the response body
                // and ensure it is fully consumed
                body = EntityUtils.toString(entity2);   
                System.out.println(body);  
                EntityUtils.consume(entity2);
               
            }catch(Exception e){
            	logger.error(":::Post Request Error.Url:" + url + ";JsonParam:" + jsonParam, e);
            }
            finally {
                response2.close();
            }
        }catch(Exception e){
        	logger.error(":::Post Request Error.Url:" + url + ";JsonParam:" + jsonParam, e);
        }
        finally {
            httpclient.close();
        }
        return body;
	}
	
	public static String postRequest(String url, Map<String, String> param, Map<String, String> headers) throws Exception{
		CloseableHttpClient httpclient = HttpClients.createDefault();
		String body = "{}";
        try {
        	
            HttpPost httpPost = new HttpPost(url);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
        	 Set<String> key = param.keySet();
             for (Iterator<String> it = key.iterator(); it.hasNext();) {
                 String k = (String) it.next();
                 nvps.add(new BasicNameValuePair(k, param.get(k)));
             }
             httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); 
            CloseableHttpResponse response2 = httpclient.execute(httpPost);

            try {
                System.out.println(response2.getStatusLine());
                HttpEntity entity2 = response2.getEntity();
                // do something useful with the response body
                // and ensure it is fully consumed
                body = EntityUtils.toString(entity2);   
                System.out.println(body);  
                EntityUtils.consume(entity2);
               
            }catch(Exception e){
            	logger.error(":::Post Request Error.Url:" + url + ";Param:" + param, e);
            }
            finally {
                response2.close();
            }
        }catch(Exception e){
        	logger.error(":::Post Request Error.Url:" + url + ";Param:" + param, e);
        }
        finally {
            httpclient.close();
        }
        return body;
	}
	
	public static String postRequest(String url, Map<String,String> param) throws Exception{
		CloseableHttpClient httpclient = HttpClients.createDefault();
		String body = "{}";
        try {
            HttpPost httpPost = new HttpPost(url);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
        	 Set<String> key = param.keySet();
             for (Iterator<String> it = key.iterator(); it.hasNext();) {
                 String k = (String) it.next();
                 nvps.add(new BasicNameValuePair(k, param.get(k)));
             }
             httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); 
            CloseableHttpResponse response2 = httpclient.execute(httpPost);

            try {
                System.out.println(response2.getStatusLine());
                HttpEntity entity2 = response2.getEntity();
                // do something useful with the response body
                // and ensure it is fully consumed
                body = EntityUtils.toString(entity2);   
                System.out.println(body);  
                EntityUtils.consume(entity2);
               
            }catch(Exception e){
            	logger.error(":::Post Request Error.Url:" + url + ";Param:" + param, e);
            }
            finally {
                response2.close();
            }
        }catch(Exception e){
        	logger.error(":::Post Request Error.Url:" + url + ";Param:" + param, e);
        }
        finally {
            httpclient.close();
        }
        return body;
	}
	
	public static void main(String[] args) {
		String url = "http://localhost:9090/pms/promotion/promotionMatch.do";
		String jsonParam = "encryptStr=UjAT2ooNbss2XlJWTQ9LMei11rAHcVNK1Fq3B8TUum6IrGKPlCM0XGmWq9uC3MCpo4aWLU9EJFOd3XXy8SIgXeKLwPzGfbZ8SZE5rRosAfeXkdFjBUmoPuuF5jWKK14otbMKKVZ1q0XgPooigXScwjJlT8zloabB%2FT55vn7b4Xnto073FecGnWErvy3Jm2xWR%2FLIwhUWgSzhKHrJoxTUgW4qdG6AVJpv0eggfty%2F30CMF7hOzD%2B6IYKDtDSM9XS8Jus9OkbxkJCBREEj8ehlOD1mNwUbFcqFU5mB%2Fdp0ZKsblYHxCgxMQYeweMKFmjKzgPvtS8YN5BxxeUtVq5OVxoNV5XWo32fJGAaPEOijDK0MiKtp%2FuPn%2FItZnSrDsK%2BjYMgfJS%2BFXWFgcXga0moQST4MJhSNb%2BGEJbRCIHtyIBFzPU%2B701Ed2zFKKzLR9lrm";
		try {
			postRequest(url,jsonParam);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
